import configUrl from '@/util/url.js'
import store from '../store/';


let config = {
	url:"",
	data:{},
	method:''
}
const request = async (config) => {
    return await new Promise((resolve, reject) => {
		let defaultConfig = {
			needAuth: 1
		}
		
		config = Object.assign({}, defaultConfig, config);
		
		uni.showLoading({
			mask: true
		});
		
		let appUrl = '';
	
		appUrl = configUrl.BASE_URL + config.url;
		
        uni.request({
            method: config.method || 'get',
            url: appUrl,
            data: config.data,
			timeout:50000,
            header: (() => {
				let base_config = {}
				
				if (config.needAuth != '0' && uni.getStorageSync('token')) {
				    base_config['Authorization'] = `Bearer ${uni.getStorageSync('token')}`;
				}
				
				if(config.isformData) {
					base_config['Content-Type'] = 'application/x-www-form-urlencoded';
				}
						
                return base_config;
            })(),
			complete:(result)=>{
				uni.hideLoading();
				
				let { data } = result;
				
				
				if(	data ) {
					if ( data.code === 200){
						resolve(data);
					} else if ( data.code === 401 ) {
						uni.showToast({
							title: '请重新登陆',
							duration: 2000,
							icon: 'none'
						});
						
						setTimeout(()=> {
							store.dispatch({type: 'logout'});
						}, 2000);
					}else{
						uni.showToast({
							title: data.msg || '',
							duration: 2000,
							icon: 'none'
						});
						
						setTimeout(()=> {
							reject();
						}, 2000)
					}
				} else {
					reject();
				}
				
			}
        })
    })
}


const uploadFile = (config) => {
	
	return new Promise((resolve, reject) => {
		let defaultConfig = {
			needAuth: 1
		}
		
		config = Object.assign({}, defaultConfig, config);
		
		uni.uploadFile({
			url: configUrl.BASE_URL + config.url, //仅为示例，非真实的接口地址
		    filePath: config.tempFilePath,
		    name: config.name,
		    formData: config.data,
			header: (() => {
				let base_config = {};
				
				if (config.needAuth !='0' && uni.getStorageSync('token')) {
				    base_config['Authorization'] = `Bearer ${uni.getStorageSync('token')}`;
				}
				
			    return base_config;
			})(),
		    complete: (uploadFileRes) => {
				let {data} = uploadFileRes;
				
				if(	data ) {
					data = JSON.parse(data);
					
					if (data.code === 200){
						resolve(data.imgUrl);
					}else{
						uni.showToast({
							title: data.msg,
							duration: 2000,
							icon: 'none'
						});
						
						setTimeout(() => {
							reject();
						} ,2000);
					}
				} else {
					reject();
				}
		    }
		});
	})
}

module.exports = {
	request,
	uploadFile
}